package com.hontech.bv.ui.view.adapter

import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.hontech.bv.R
import com.hontech.bv.conn.Device
import com.hontech.bv.conn.Proto
import com.hontech.bv.http.FirmInfo
import com.hontech.bv.http.downloadFirm
import com.hontech.bv.http.downloadForBrowser
import com.hontech.bv.task.onClick
import com.hontech.bv.ui.window.showProg
import com.hontech.bv.utils.parseTimestamp

class FirmRvItem(private val destId: Int, view: View) : RecyclerView.ViewHolder(view) {

    private val tvVersion = view.findViewById<TextView>(R.id.id_item_firm_tv_version)
    private val tvDate = view.findViewById<TextView>(R.id.id_item_firm_tv_date)
    private val tvDescribe = view.findViewById<TextView>(R.id.id_item_firm_tv_describe)
    private val btnUpdate = view.findViewById<Button>(R.id.id_item_firm_btn_update)

    fun setUp(firmInfo: FirmInfo) {
        tvVersion.text = firmInfo.version
        tvDate.text = parseTimestamp(firmInfo.createTimestamp)
        tvDescribe.text = firmInfo.describe

        if (destId == Proto.ID_IPC) {
            btnUpdate.onClick { onApkUpdate(firmInfo) }
        } else {
            btnUpdate.onClick { update(firmInfo) }
        }

    }

    private suspend fun onApkUpdate(firmInfo: FirmInfo) {
        downloadForBrowser(firmInfo.id)
    }

    private suspend fun update(firmInfo: FirmInfo) {
        val dialog = showProg("${Proto.nameId(destId)}升级", "下载固件")
        try {
            val data = downloadFirm(firmInfo.id)
            dialog.setMsg("下载成功 开始更新")
            Device.ota(destId, data) {
                dialog.setMsg("进度:${it}%")
            }
            dialog.success("更新成功")
        } catch (e: Exception) {
            e.printStackTrace()
            dialog.error(e)
        }
    }
}

